/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.util;

import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.isfd.constant.enums.CompressionTypeEnum;
import com.comac.ins.isfd.domain.vo.TreeNodeVo;
import lombok.extern.slf4j.Slf4j;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 压缩文件处理工具类
 *
 * @author hxloongs
 * @date 2024-8-14
 */
@Slf4j
public class CompressUtils {


    public static List<String> extractZipReturnPathList(File zipFile, File extractDir, String charset, Boolean writeToDisk) throws IOException {
        List<String> resultList = new ArrayList<>();
        try (ZipFile zip = new ZipFile(zipFile, Charset.forName(charset))) {
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String path = entry.getName();
                File file = new File(extractDir, path);

                File parentDir = file.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    parentDir.mkdirs();
                }

                if (!entry.isDirectory() && writeToDisk) {
                    try (OutputStream os = new FileOutputStream(file);
                         InputStream is = zip.getInputStream(entry)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) > 0) {
                            os.write(buffer, 0, len);
                        }
                    }
                }
                if (file.isFile()) {
                    // 收集解压出来的路径
                    resultList.add(file.getPath());
                }
            }
        }
        return resultList;
    }

    public static List<String> extractRarReturnPathList(File rarFile, File extractDir, Boolean writeToDisk) throws IOException {
        String rarDir = rarFile.getAbsolutePath();
        String outDir = extractDir.getAbsolutePath() + File.separator;
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;

        List<String> resultList = new ArrayList<>();

        try {
            randomAccessFile = new RandomAccessFile(rarDir, "r");
            inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
            ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
            for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                String itemName = item.getPath();
                File itemFile = new File(extractDir, itemName);
                File parentDir = itemFile.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    parentDir.mkdirs();
                }
                if (!item.isFolder() && writeToDisk) {
                    final int[] hash = new int[]{0};
                    final long[] sizeArray = new long[1];
                    File outFile = new File(outDir + item.getPath());
                    try (FileOutputStream fos = new FileOutputStream(outFile)) {
                        item.extractSlow(data -> {
                            try {
                                IOUtils.write(data, fos);
                            } catch (Exception e) {
                                log.error("Error writing to file: {}", outFile.getAbsolutePath(), e);
                            }
                            hash[0] ^= Arrays.hashCode(data);
                            sizeArray[0] += data.length;
                            return data.length;
                        });
                    }
                }
                if (itemFile.isFile()) {
                    // 收集解压出来的路径
                    resultList.add(itemFile.getPath());
                }
            }
        } finally {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        }
        return resultList;
    }

    public static List<String> getRelativeFilePaths(Path directoryPath) {
        try (Stream<Path> paths = Files.walk(directoryPath)) {
            return paths
                .filter(Files::isRegularFile) // 只保留文件
                .map(Path::toString) // 转换为字符串
                .collect(Collectors.toList()); // 收集到List中
        } catch (IOException e) {
            throw new RuntimeException("Error walking the directory: " + directoryPath, e);
        }
    }


    public static TreeNodeVo buildTreeAndExtractZip(File zipFile, File extractDir, String charset, Boolean writeToDisk) throws IOException {
        TreeNodeVo root = new TreeNodeVo(extractDir.getName(), true, extractDir);

        try (ZipFile zip = new ZipFile(zipFile, Charset.forName(charset))) {
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String path = entry.getName();
                File file = new File(extractDir, path);


                File parentDir = file.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    parentDir.mkdirs();
                }

                if (!entry.isDirectory() && writeToDisk) {
                    try (OutputStream os = new FileOutputStream(file);
                         InputStream is = zip.getInputStream(entry)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) > 0) {
                            os.write(buffer, 0, len);
                        }
                    }
                }


                addEntryToTree(root, path, entry.isDirectory(), file, CompressionTypeEnum.ZIP.getValue());
            }
        }

        return root;
    }


    public static TreeNodeVo buildTreeAndExtractRar(File rarFile, File extractDir, Boolean writeToDisk) throws IOException {
        TreeNodeVo root = new TreeNodeVo(extractDir.getName(), true, extractDir);
        String rarDir = rarFile.getAbsolutePath();
        String outDir = extractDir.getAbsolutePath() + File.separator;

        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;

        try {
            randomAccessFile = new RandomAccessFile(rarDir, "r");
            inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
            ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();

            for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {


                String itemName = item.getPath();


                File itemFile = new File(outDir, itemName);


                File parentDir = itemFile.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    parentDir.mkdirs();
                }

                if (!item.isFolder() && writeToDisk) {
                    final int[] hash = new int[]{0};
                    final long[] sizeArray = new long[1];
                    File outFile = new File(outDir + item.getPath());
                    try (FileOutputStream fos = new FileOutputStream(outFile)) {
                        item.extractSlow(data -> {
                            try {
                                IOUtils.write(data, fos);
                            } catch (Exception e) {
                                log.error("Error writing to file: {}", outFile.getAbsolutePath(), e);
                            }
                            hash[0] ^= Arrays.hashCode(data);
                            sizeArray[0] += data.length;
                            return data.length;
                        });
                    }
                }


                addEntryToTree(root, itemName, item.isFolder(), itemFile, CompressionTypeEnum.RAR.getValue());
            }
        } finally {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        }

        return root;
    }

    private static void addEntryToTree(TreeNodeVo parent, String path, boolean isDirectory, File file, String type) {
        String[] parts = null;
        if (CompressionTypeEnum.RAR.getValue().equals(type)) {
            parts = path.split("\\\\");
        } else if (CompressionTypeEnum.ZIP.getValue().equals(type)) {
            parts = path.split("/");
        } else {
            throw new BaseException("暂时不支持该类型解压！");
        }
        TreeNodeVo currentParent = parent;

        for (String part : parts) {
            if (part.isEmpty()) continue;

            TreeNodeVo child = findOrCreateChild(currentParent, part, isDirectory, file);
            currentParent = child;
            file = new File(file, part);
        }
    }

    private static TreeNodeVo findOrCreateChild(TreeNodeVo parent, String name, boolean isDirectory, File file) {
        for (TreeNodeVo child : parent.getChildren()) {
            if (child.getName().equals(name)) {
                return child;
            }
        }

        TreeNodeVo newNode = new TreeNodeVo(name, isDirectory, file);
        parent.getChildren().add(newNode);
        return newNode;
    }


    public static void main(String[] args) {
        try {
//            File zipFile = new File("C:\\Users\\86166\\Desktop\\test2\\zip\\型材库.zip");
//            File extractDirZip = new File("C:\\Users\\86166\\Desktop\\test2\\zip");
//
//
//            if (!extractDirZip.exists()) {
//                extractDirZip.mkdirs();
//            }
//
//            TreeNodeVo treeRootZip = buildTreeAndExtractZip(zipFile, extractDirZip, System.getProperty("sun.jnu.encoding"), Boolean.TRUE);
//            printTree(treeRootZip, 0);
//
//
//            File rarFile = new File("C:\\Users\\86166\\Desktop\\test2\\rar\\型材库.rar");
//            File extractRarDir = new File("C:\\Users\\86166\\Desktop\\test2\\rar");
//
//
//            if (!extractRarDir.exists()) {
//                extractRarDir.mkdirs();
//            }
//
//            TreeNodeVo treeRootRar = buildTreeAndExtractRar(rarFile, extractRarDir, Boolean.TRUE);
//            printTree(treeRootRar, 0);


//            File zipFilePath = new File("C:\\Users\\86166\\Desktop\\要素库项目\\模型管理\\test_file\\zip\\C919_10002.zip");
//            File extractDirZipPath = new File("C:\\Users\\86166\\Desktop\\要素库项目\\模型管理\\test_file\\zip");
//            if (!extractDirZipPath.exists()) {
//                extractDirZipPath.mkdirs();
//            }
//            List<String> paths = extractZipReturnPathList(zipFilePath, extractDirZipPath, System.getProperty("sun.jnu.encoding"), Boolean.TRUE);
//
//            System.out.println("===================================");
//            paths.forEach(System.out::println);


            File zipFilePath1 = new File("C:\\Users\\hxloo\\Desktop\\要素库项目\\模型库&结果库对比需求\\model.rar");
            long t = System.currentTimeMillis();
            File extractDirZipPath1 = new File("/data/mesh/C919/20250109批次/" + t);
            if (!extractDirZipPath1.exists()) {
                extractDirZipPath1.mkdirs();
            }
            List<String> paths1 = extractRarReturnPathList(zipFilePath1, extractDirZipPath1, Boolean.TRUE);

            paths1.forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void printTree(TreeNodeVo node, int level) {
        for (int i = 0; i < level; i++) {
            System.out.print("\t");
        }
        System.out.println((node.isDirectory() ? "Folder" : "File") + ": " + node.getName() + " [" + node.getFile().getAbsolutePath() + "]");

        for (TreeNodeVo child : node.getChildren()) {
            printTree(child, level + 1);
        }
    }
}
